package com.ruoyi.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.param.impl.IdParam;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.order.domain.Manuscript;
import com.ruoyi.order.service.IManuscriptService;
import com.ruoyi.oss.service.OssService;

/**
 * 稿件Controller
 * 
 * @author ruoyi
 * @date 2024-01-08
 */
@RestController
@RequestMapping("/system/manuscript")
public class ManuscriptController extends BaseController {
	@Autowired
	private IManuscriptService manuscriptService;

	OssService ossService;

	@Resource
	public void setOssService(OssService ossService) {
		this.ossService = ossService;
	}

	/**
	 * 查询稿件列表
	 */
    @PreAuthorize("@ss.hasPermi('order:file:manager')")
	@PostMapping("/listByOrderId")
	public AjaxResult listByOrderId(@RequestBody @Validated IdParam param) {
		List<Manuscript> list = manuscriptService.selectListById(param.getId());
		return AjaxResult.success(list);
	}

	@DeleteMapping("/{id}")
	@PreAuthorize("@ss.hasPermi('order:file:delete')")
	public AjaxResult deleteByOrderId(@PathVariable int id) {

		Manuscript selectById = this.manuscriptService.selectById(id);

		List<String> strings = new ArrayList<String>();

		strings.add(selectById.getFile().substring(1));
		
		Integer deleteFileToOSS = this.ossService.deleteFileToOSS(strings);
		
		if (1 != deleteFileToOSS) {
			return AjaxResult.error("删除失败");
		}
		
		int deleteById = manuscriptService.deleteById(id);

		return AjaxResult.success(deleteById);
	}
	
	/**
	 * 上传稿件
	 * @param files
	 * @return
	 */
	@PutMapping(value = "/{id}")
	public AjaxResult uploadManuscript(@RequestBody List<Manuscript> files, @PathVariable Integer id) {
		
		int batchInsert = this.manuscriptService.batchInsert(files, id);
		
		return AjaxResult.success(batchInsert);
	}
}